package com.interprise.shiro.utils;

import org.apache.shiro.crypto.hash.Md5Hash;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    public static final String KEY_MD5 = "MD5";
    public static final String CHAR_SET = "utf-8";

    public static String encrypt(String data) throws NoSuchAlgorithmException ,UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
        md5.update(data.getBytes(CHAR_SET));
        return byte2hexString(md5.digest());
    }
	/**
	 * 把加密后的字节数组(byte[])转换为字符串(String)
	 * @param bytes
	 * @return
	 */
	private static String byte2hexString(byte[] bytes) {
		StringBuilder buf = new StringBuilder(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString();
	}


	public static void main(String[] args) {

		Md5Hash hash = new Md5Hash();
	}
}
